#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

void add(MYSQL *mysql)
{
    char *sql = "insert into test_tb values(NULL, 22, '小高', 88);";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query failed, err: %d, error: %s\n", mysql_errno(mysql), mysql_error(mysql));
        return;
    }
}

void mod(MYSQL *mysql)
{
    char *sql = "update test_tb set age=25 where name='小高';";
    int ret = mysql_query(mysql,sql);
    if (ret != 0)
    {
        printf("mysql query failed, err: %d, error: %s\n", mysql_errno(mysql), mysql_error(mysql));
        return;
    }
}

void del(MYSQL *mysql)
{
    char *sql = "delete from test_tb where name='小高';";
    int ret = mysql_query(mysql,sql);
    if (ret != 0)
    {
        printf("mysql query failed, err: %d, error: %s\n", mysql_errno(mysql), mysql_error(mysql));
        return;
    }
}

void get(MYSQL *mysql)
{
    char *sql = "select * from test_tb;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query failed, err: %d, error: %s\n", mysql_errno(mysql), mysql_error(mysql));
        return;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == NULL)
    {
        printf("mysql store result error:%s\n", mysql_error(mysql));
        return;
    }
    int row = mysql_num_rows(res);
    int col = mysql_num_fields(res);
    printf("%10s%10s%10s%10s\n", "ID", "年龄", "姓名", "成绩");
    for (int i = 0; i < row; i++)
    {
        MYSQL_ROW row_data = mysql_fetch_row(res);
        for (int i = 0; i < col; i++)
        {
            printf("%10s", row_data[i]);
        }
        printf("\n");
    }
    mysql_free_result(res);
    return;
}

int main()
{
    MYSQL *mysql = mysql_init(NULL);

    if ((mysql_real_connect(mysql, "127.0.0.1", "root", "123456", "test_db", 0, NULL, 0)) == NULL)
    {
        printf("mysql connect failed: %d, error: %s\n", mysql_errno(mysql), mysql_error(mysql));
        return -1;
    }
    mysql_set_character_set(mysql, "utf8");

    //add(mysql);
    //add(mysql);
    //mod(mysql);
    //del(mysql);
    get(mysql);
    mysql_close(mysql);  // 关闭连接
    return 0;
}
